package com.sunseen.capacitormachine.common;

import android.content.Context;
import android.util.Log;
import android.widget.Toast;

import com.dslplatform.json.DslJson;
import com.dslplatform.json.runtime.Settings;
import com.sunseen.capacitormachine.BuildConfig;
import com.sunseen.capacitormachine.common.event.BatchIdStatusUpdateEvent;
import com.sunseen.capacitormachine.commumication.http.HttpUtil;
import com.sunseen.capacitormachine.commumication.http.RestClient;
import com.sunseen.capacitormachine.commumication.http.callback.IError;
import com.sunseen.capacitormachine.commumication.http.callback.IFailure;
import com.sunseen.capacitormachine.commumication.http.callback.ISuccess;

import org.greenrobot.eventbus.EventBus;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Calendar;

public class MethodUtil {

    private static final DslJson<Object> serializeDslJson = new DslJson<>(Settings.basicSetup().allowArrayFormat(true));
    private static final ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    public static byte[] Object2JSONBytes(Object obj) {
        try {
            outputStream.reset();
            serializeDslJson.serialize(obj, outputStream);
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static final DslJson<Object> deserializeDslJson = new DslJson<>(Settings.basicSetup().allowArrayFormat(true));
    private static ByteArrayInputStream inputStream;

    public static <T extends Object> T jsonString2Pojo(Class<T> clazz, String string) {
        inputStream = new ByteArrayInputStream(string.getBytes());
        try {
            return deserializeDslJson.deserialize(clazz, inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getNoNullString(String str) {
        return str != null ? str : "";
    }

    public static String createStringUnit(String intString, int decimalCount, String unit) {
        if (intString != null) {
            try {
                int value = Integer.parseInt(intString);
                return createStringUnit(value, decimalCount, unit);
            } catch (NumberFormatException e) {
                return "";
            }
        } else {
            return "";
        }
    }

    public static String createStringUnit(int value, int decimalCount, String unit) {
        if (decimalCount > 0) {
            float divisor = 1f;
            for (int i = 0; i < decimalCount; i++) {
                divisor *= 10;
            }
            return value / divisor + unit;
        } else {
            return value + unit;
        }
    }

    private static final String V = "V";

    public static String createVUnit(String str) {
        return MethodUtil.createStringUnit(str, 1, V);
    }

//    public static void main(String[] args) {
//        String str = createCapacityIUnit(3600+"");
//        System.out.println("xxxxx : " + str);
//    }

    private static final String UA = "uA";

    public static String createCapacityIUnit(String str) {
        return MethodUtil.createStringUnit(str, 1, UA);
    }

    private static final String A = "A";

    public static String createIUnit(String str) {
        return MethodUtil.createStringUnit(str, 2, A);
    }

    private static final String UF = "μF";

    public static String createCapacityUnit(String str) {
        return MethodUtil.createStringUnit(str, 1, UF);
    }

    private static final char[] b = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    /**
     * 将十进制数转换成十六进制StringBuilder
     */
    public static StringBuilder intToHex(int n) {
        if (n != 0) {
            StringBuilder sb = new StringBuilder(2);

            while (n != 0) {
                sb = sb.append(b[n % 16]);
                n = n / 16;
            }
            if (sb.length() == 1) {
                sb = sb.append(0);
            }
            return sb.reverse();
        } else {
            return new StringBuilder("00");
        }
    }

    /**
     * @param bytes    打印的目标byte数组
     * @param startPos 目标数组的起始打印位置
     * @param endPos   目标数组结束的打印位置(不包含该位)
     * @param wrap     打印的log每多少位数字换行
     */
    public static void logHexBytes(String tag, byte[] bytes, int startPos, int endPos, int wrap) {
        if (BuildConfig.DEBUG && endPos > startPos) {
            StringBuilder sb = new StringBuilder(2 * endPos - startPos);
            for (int i = startPos; i < endPos; i++) {
                if ((i - startPos) % wrap == 0) {
                    sb.append('\n');
                }
                sb.append(MethodUtil.intToHex(bytes[i] & 0xFF));
                sb.append(" ");
            }
            Log.e(tag, sb.toString());
        }
    }

    /**
     * 获取屏幕高度(px)
     */
    public static int getScreenHeight(Context context) {
        return context.getResources().getDisplayMetrics().heightPixels;
    }

    /**
     * 获取屏幕宽度(px)
     */
    public static int getScreenWidth(Context context) {
        return context.getResources().getDisplayMetrics().widthPixels;
    }

    public static String getCapacitorId(String uid) {
        if (uid != null && uid.length() > 0) {
            String[] strings = uid.split("_");
            if (strings.length > 0) {
                return strings[0];
            }
        }
        return "";
    }

    public static boolean isDateCorrect(Context context, String yearStr, String monthStr, String dayStr) {
        int year = Integer.valueOf(yearStr);
        if (year < 1970) {
            Toast.makeText(context, "请输入大于或等于1970的年份", Toast.LENGTH_SHORT).show();
            return false;
        }

        int month = Integer.valueOf(monthStr);
        if (month < 1 || month > 12) {
            Toast.makeText(context, "请输入1~12的月份", Toast.LENGTH_SHORT).show();
            return false;
        }

        int day = Integer.valueOf(dayStr);
        if (day < 1 || day > 31) {
            Toast.makeText(context, "请输入1~31的日期值", Toast.LENGTH_SHORT).show();
            return false;
        }
        return true;
    }

    //获取传入的当天的第一个小时的第一分钟第一秒的时间戳 以秒为单位
    public static long getStartTimeStamp(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day, 0, 0, 0);
        return calendar.getTimeInMillis() / 1000;
    }

    //获取传入的当天的最后一个小时的最后一分钟最后一秒的时间戳 以秒为单位
    public static long getEndTimeStamp(int year, int month, int day) {
        Calendar calendar = Calendar.getInstance();
        calendar.set(year, month, day, 23, 59, 59);
        return calendar.getTimeInMillis() / 1000;
    }

    /**
     * 向服务器请求更新该批次号生产参数的生产状态
     *
     * @param batchId 要更改的生产参数的批次号
     * @param status  要更新的生产状态 0 待生产  1 生产中  2 已生产
     */
    public static void updateBatchProduceStatus(final String batchId, final int status) {
        RestClient.builder()
                .url(HttpUtil.UpdateBatchIdStatus)
                .params("batchId", batchId)
                .params("status", status)
                .success(new ISuccess() {
                    @Override
                    public void onSuccess(String response) {
                        Log.e("test", "updateBatchProduceStatus onSuccess ");
                        EventBus.getDefault().post(new BatchIdStatusUpdateEvent(batchId, status, true));
                    }
                })
                .failure(new IFailure() {
                    @Override
                    public void onFailure() {
                        EventBus.getDefault().post(new BatchIdStatusUpdateEvent(batchId, status, false));
                        Log.e("test", "updateBatchProduceStatus onFailure ");
                    }
                })
                .error(new IError() {
                    @Override
                    public void onError(int code, String msg) {
                        EventBus.getDefault().post(new BatchIdStatusUpdateEvent(batchId, status, false));
                        Log.e("test", "updateBatchProduceStatus onError ");
                    }
                })
                .build()
                .post();
    }

    /**
     * 截断输出日志
     * @param msg
     */
    public static void loge(String tag, String msg) {
        if (tag == null || tag.length() == 0
                || msg == null || msg.length() == 0)
            return;

        int segmentSize = 3 * 1024;
        long length = msg.length();
        if (length <= segmentSize ) {// 长度小于等于限制直接打印
            Log.e(tag, msg);
        }else {
            while (msg.length() > segmentSize ) {// 循环分段打印日志
                String logContent = msg.substring(0, segmentSize );
                msg = msg.replace(logContent, "");
                Log.e(tag,"-------------------"+ logContent);
            }
            Log.e(tag,"-------------------"+ msg);// 打印剩余日志
        }
    }

}
